<?php

use GatewayWorker\Lib\Db;
use GatewayWorker\Lib\Gateway;


class Events
{
    public static function onConnect($client_id)
    {

    }

    public static function test() {
        $db1 = Db::instance('db1');
        $jt = $db1->select('*')
            ->from('fa_tzxbs_jt')
            ->where('jt_serial= :jt_serial')
            ->where('jt_serial0= :jt_serial0')
            ->bindValues(array('jt_serial' => 'C39E03', 'jt_serial0' => 'AI-THINKER'))
            ->row();

        if ($jt) {
            $id = $jt['id'];//648
            return;
        }
    }

    public static function onMessage($client_id, $message)
    {
//        Gateway::sendToClient($client_id, $message.",\"AI-THINKER_123\"");
//        Events::test();
//        return;

        try {
            $db1 = Db::instance('db1');
            $message = str_replace(array("\r\n", "\r", "\n"), "", $message);
            $insert_id = $db1->insert('test')->cols(array('name' => "client_id=" . $client_id . " --- TZ_onMessage=" . $message))->query();

            if (strncmp($message, ">", 1) == 0) {
                $v = explode("*", $message);
                if (count($v) > 1) {
                    $value = $v[0];
                    $v1 = explode(",", $v[0]);
                    if (count($v1) > 2) {
                        $deviceid = str_replace(">", '', $v1[0]);
                        $command = $v1[1];
                        $content = $v1[2];

                        $id = $db1->select('id')
                            ->from('fa_taizhu_device')
                            ->where('deviceid= :deviceid')
                            ->bindValues(array('deviceid' => $deviceid))
                            ->single();

                        $data = array(
                            'client_id' => $client_id,
                            'isonline' => 1,
                            'update_time' => date('Y-m-d H:i:s', time())
                        );

                        if ($command == "FE01") {
                            $data['fe01'] = $content;
                        } else if ($command == "FE02") {
                            $data['fe02'] = $content;
                        }

                        if (empty($id)) {
                            $data['deviceid'] = $deviceid;
                            $device_id = $db1->insert('fa_taizhu_device')->cols($data)->query();
                        } else {
                            $db1->update('fa_taizhu_device')->cols($data)->where("id=" . $id)->query();
                        }

                        $data = array(
                            'deviceid' => $deviceid,
                            'command' => $command,
                            'content' => $content
                        );
                        $db1->insert('fa_taizhu_records')->cols($data)->query();

                        // 當裝置出貨時，進行紀錄-->
                        $jt_serial0 = "AI-THINKER";
                        if (false !== strpos($deviceid, "DF-COMPANY")) {
                            $jt_serial0 = "DF-COMPANY";
                            $jt_serial = str_replace('DF-COMPANY_', '', $deviceid);
                        } else if (false !== strpos($deviceid, "AI-COMPANY")) {
                            $jt_serial0 = "AI-COMPANY";
                            $jt_serial = str_replace('AI-COMPANY_', '', $deviceid);
                        } else if (false !== strpos($deviceid, "DF-THINKER")) {
                            $jt_serial0 = "DF-THINKER";
                            $jt_serial = str_replace('DF-THINKER_', '', $deviceid);
                        } else {
                            $jt_serial = str_replace('AI-THINKER_', '', $deviceid);
                        }

                        $jt = $db1->select('*')
                            ->from('fa_tzxbs_jt')
                            ->where('jt_serial= :jt_serial')
                            ->where('jt_serial0= :jt_serial0')
                            ->bindValues(array('jt_serial' => $jt_serial, 'jt_serial0' => $jt_serial0))
                            ->row();

                        if ($jt) {
                            $money = intval($content);
                            if ($command == "FE00") {
                                //自動消保
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'command' => "自動消保",
                                    'money' => $money  // 最后投币金额
                                );
                                $db1->insert('fa_tzxbs_receipts')->cols($data)->query();

                                $data = array(
                                    'money' => 0
                                );
                                $db1->update('fa_tzxbs_jt')->cols($data)->where("id=" . $jt['id'])->query();

                                //sns 機台名稱，自動消保，消保金額:XXX 元!
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'content' => $jt['name'] . "，自動消保，消保金額: " . $money . " 元!",
                                    'createtime' => time()
                                );
                                $db1->insert('fa_tzxbs_sns')->cols($data)->query();

                            } else if ($command == "FE01") {
                                //投幣--目前幣量只有FE01
                                //只有FE01會帶金額，其他的都不會有金額
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'command' => "投幣金額",
                                    'money' => $money   //目前累加金额
                                );
                                $db1->insert('fa_tzxbs_receipts')->cols($data)->query();

                                $data = array(
                                    'money' => $money
                                );
                                $db1->update('fa_tzxbs_jt')->cols($data)->where("id=" . $jt['id'])->query();

                                //sns 機台名稱，有投幣，目前幣量:XXXX 元!
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'content' => $jt['name'] . "，有投幣，目前幣量: " . $money . " 元!",
                                    'createtime' => time()
                                );
                                $db1->insert('fa_tzxbs_sns')->cols($data)->query();

                            } else if ($command == "FE02") {
                                //出貨---FE02表示機台的娃娃被夾到
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'command' => "出貨",
                                    'money' => $money //最后投币金额
                                );
                                $db1->insert('fa_tzxbs_receipts')->cols($data)->query();

                                // 理解不了的
                                $data = array(
                                    'money' => 0
                                );
                                $db1->update('fa_tzxbs_jt')->cols($data)->where("id=" . $jt['id'])->query();

                                //sns 機台名稱，有出貨!
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'content' => $jt['name'] . "，有出貨，投幣金額：" . $money . "元！",
                                    'createtime' => time()
                                );
                                $db1->insert('fa_tzxbs_sns')->cols($data)->query();

                            } else if ($command == "FE03") {
                                //強制消保
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'command' => "強制消保",
                                    'money' => $money  //最后投币金额
                                );
                                $db1->insert('fa_tzxbs_receipts')->cols($data)->query();

                                $data = array(
                                    'money' => 0
                                );
                                $db1->update('fa_tzxbs_jt')->cols($data)->where("id=" . $jt['id'])->query();

                            } else if ($command == "FE04") {
                                //設置自動消保
                                //>AI-THINKER_A8CA56,FE04,0000,%04d,%04d*
                                $auto_switch = "開啟";
                                if ($v1[2] == '0000') {
                                    $auto_switch = "關閉";
                                }
                                $zdxb = intval($v1[3]);
                                $time = intval($v1[4]);
                                $hour = intval($time / 60);
                                $minute = $time % 60;
                                $command = $auto_switch . "設置自動消保: 金額{$zdxb}，時間: {$hour} 小時 {$minute} 分鐘";
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'command' => $command,
                                );
                                $db1->insert('fa_tzxbs_receipts')->cols($data)->query();
                            } else if ($command == "FE05") {
                                //設置保夾金額
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'command' => "設置保夾金額",
                                    'money' => $money  //最后投币金额
                                );
                                $db1->insert('fa_tzxbs_receipts')->cols($data)->query();

                            } else if ($command == "FE06") {
                                //強制重啟
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'command' => "機台重啟",
                                );
                                $db1->insert('fa_tzxbs_receipts')->cols($data)->query();

                            } else if ($command == "FE99") {
                                //機台上線
                                $data = array(
                                    'jt_id' => $jt['id'],
                                    'command' => "機台上線",
                                );
                                $db1->insert('fa_tzxbs_receipts')->cols($data)->query();
                            }
                        }
                        Gateway::sendToClient($client_id, "OK");
                    }
                }
            }


        } catch (\Exception $e) {
            exit(250);
        } catch (\Error $e) {
            exit(250);
        }

    }

    public static function onClose($client_id)
    {
        $db1 = Db::instance('db1');
        $device_id = $db1->select('id')
            ->from('fa_taizhu_device')
            ->where('client_id= :client_id')
            ->orderByDESC(array('update_time'))
            ->limit(1)
            ->bindValues(array('client_id' => $client_id))
            ->single();

        if (!empty($device_id)) {
            $data = array(
                'isonline' => 0,
                'update_time' => date('Y-m-d H:i:s', time())
            );
            $db1->update('fa_taizhu_device')->cols($data)->where("id=" . $device_id)->query();
        }
    }

    public static function getXOR($value)
    {
        if (empty($value)) {
            return "";
        }
        $aa = "";
        for ($i = 0; $i < strlen($value); $i++) {
            $bb = substr($value, $i, 1);
            if ($i == 0) {
                $aa = $bb;
            } else {
                $aa = $aa ^ $bb;
            }
        }

        $s1 = strtoupper(bin2hex($aa));
        return $s1;
    }

//請在收到自動消保、強制消保、出貨時， 將目前累計投幣量清零
//FE00:Device送出自動消保訊息
//FE02:Device送出出貨訊息
//FE03:Device送出強制消保

}
